import 'package:enterprise_v6_app/app/components/special_operation/custom_select_function.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/ext/widget_extension.dart';
import 'package:enterprise_v6_app/app/data/entities/application/special_list/apply_user_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/special_list/identification_config_entity.dart';
import 'package:enterprise_v6_app/app/modules/application/special_operation/special_list/job_plan_request/plan_risk_identification/plan_risk_identification_controller.dart';

/// 风险辨识页面
class PlanRiskIdentificationWidget extends StatelessWidget {
  PlanRiskIdentificationWidget({super.key});

  final controller = Get.put(PlanRiskIdentificationController());

  /// 选择框
  /// 涉及作业判断依据：
  // 根据辨识结果所绑定的作业类型及工器具所绑定的辨识结果判断涉及作业
  Widget _selectWidget(String title, String hintText, {required Function() callback, bool isVisibility = true}) {
    return Row(
      children: [
        AppGaps.hGap16,
        Text(
          isVisibility ? '*' : '',
          style: TextStyle(
            fontSize: 16.sp,
            color: AppColors.meaning_color_danger,
          ),
        ),
        Text(
          title,
          style: TextStyle(
            fontSize: 14.sp,
            color: AppColors.font_color_black,
          ),
        ),
        Expanded(
          child: SizedBox(
            height: 50.w,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Text(
                  hintText == '' ? '请选择' : hintText,
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: AppColors.text_grey,
                  ),
                ),
                AppGaps.hGap10,
                Icon(Icons.arrow_forward_ios, size: 14.sp, color: AppColors.text_grey),
              ],
            ),
          ),
        ),
        AppGaps.hGap16,
      ],
    ).click(callback);
  }

  //选择风险辨识结果
  _selectRiskIdentificationResult() {
    CustomSelectFunction.selectMultipleBottomSheet<IdentificationConfigEntity>(
      title: '风险辨识结果选择',
      dataList: controller.riskIdentificationList,
      checkedList: controller.riskIdentificationResult,
      onCallBack: (value) {
        controller.riskIdentificationResult = value;
        controller.update();
      },
    );
  }

  // 风险辨识结果集
  Widget _riskIdentificationResultWidget() {
    if (controller.riskIdentificationResult.isEmpty) {
      return Divider(height: 1.w, color: AppColors.bg_color_grey);
    }
    return Container(
      alignment: Alignment.centerLeft,
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      padding: EdgeInsets.all(10.w),
      decoration: BoxDecoration(
        color: const Color(0xffF7F7FB),
        borderRadius: BorderRadius.circular(4.w),
        border: Border.all(
          color: const Color(0xffEBEDF0),
          width: 1.w,
        ),
      ),
      child: Wrap(
        spacing: 10.w,
        runSpacing: 10.w,
        children: controller.riskIdentificationResult
            .map((e) => Container(
                  padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 3.w),
                  decoration: BoxDecoration(
                    color: AppColors.bg_color_grey,
                    borderRadius: BorderRadius.circular(7.w),
                    border: Border.all(
                      color: AppColors.blue_button,
                      width: 1.w,
                    ),
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                        e.identification ?? '',
                        style: TextStyle(
                          fontSize: 12.sp,
                          color: AppColors.blue_button,
                        ),
                      ),
                      AppGaps.hGap5,
                      Icon(Icons.close, size: 14.sp, color: AppColors.blue_button),
                    ],
                  ),
                ).click(() {
                  controller.riskIdentificationResult.remove(e);
                  controller.update();
                }))
            .toList(),
      ),
    );
  }

  // 工具集结果
  Widget _toolSetWidget() {
    if (controller.toolSet.isEmpty) {
      return Divider(height: 1.w, color: AppColors.bg_color_grey);
    }
    return Container(
      alignment: Alignment.centerLeft,
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      padding: EdgeInsets.all(10.w),
      decoration: BoxDecoration(
        color: const Color(0xffF7F7FB),
        borderRadius: BorderRadius.circular(4.w),
        border: Border.all(
          color: const Color(0xffEBEDF0),
          width: 1.w,
        ),
      ),
      child: Wrap(
        spacing: 10.w,
        runSpacing: 10.w,
        children: controller.toolSet
            .map((e) => Container(
                  padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 3.w),
                  decoration: BoxDecoration(
                    color: AppColors.bg_color_grey,
                    borderRadius: BorderRadius.circular(7.w),
                    border: Border.all(
                      color: AppColors.blue_button,
                      width: 1.w,
                    ),
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                        e.workTool ?? '',
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: AppColors.blue_button,
                        ),
                      ),
                      AppGaps.hGap5,
                      Icon(Icons.close, size: 14.sp, color: AppColors.blue_button),
                    ],
                  ),
                ).click(() {
                  controller.toolSet.remove(e);
                  controller.update();
                }))
            .toList(),
      ),
    );
  }

  // 下一步按钮
  Widget _nextButton() {
    return Container(
        padding: EdgeInsets.symmetric(horizontal: 15.w, vertical: 16.w),
        alignment: Alignment.centerLeft,
        child: Row(
          children: [
            Expanded(
                child: Text(
              '提示：应开据 ${controller.recommendType} 作业票！',
              style: TextStyle(
                fontSize: 12.sp,
                color: AppColors.text_red,
              ),
            )),
            AppGaps.hGap10,
            Container(
              height: 30.w,
              width: 90.w,
              color: Colors.white,
              child: ElevatedButton(
                style: ElevatedButton.styleFrom(
                  padding: EdgeInsets.zero,
                  backgroundColor: AppColors.blue_button,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20.r),
                  ),
                ),
                onPressed: controller.queryJobList,
                child: Text(
                  '重新选择',
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: Colors.white,
                  ),
                ),
              ),
            )
          ],
        ));
  }

  // 涉及作业
  Widget _involvedOperation() {
    return Column(
      children: [
        Row(
          children: [
            AppGaps.hGap16,
            Text(
              '*',
              style: TextStyle(
                fontSize: 16.sp,
                color: AppColors.meaning_color_danger,
              ),
            ),
            Text(
              '涉及作业',
              style: TextStyle(
                fontSize: 14.sp,
                color: AppColors.font_color_black,
              ),
            ),
          ],
        ),
        GridView.custom(
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 15.w),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            mainAxisSpacing: 13.w,
            crossAxisSpacing: 15.w,
            childAspectRatio: 2.5,
          ),
          childrenDelegate: SliverChildBuilderDelegate(
            (context, index) {
              final bool isSelect = controller.selectedJobList.contains(controller.workType[index]);
              return Container(
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  color: isSelect ? AppColors.blue_button : AppColors.bg_color_grey,
                  borderRadius: BorderRadius.circular(4.w),
                ),
                child: Text(
                  controller.workType[index].dictionaryLabel ?? '',
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: isSelect ? Colors.white : AppColors.text_grey,
                  ),
                ),
              ).click(() {
                controller.designJobClick(controller.workType[index]);
              });
            },
            childCount: controller.workType.length,
          ),
        ),
        Container(
          height: 1.w,
          margin: EdgeInsets.symmetric(horizontal: 16.w),
          color: AppColors.button_grey,
        )
      ],
    );
  }

  // 作业申请人
  Widget _applicant() {
    return Container(
      padding: EdgeInsets.only(left: 16.w, top: 15.w),
      child: Row(
        children: [
          Text(
            '*',
            style: TextStyle(
              fontSize: 16.sp,
              color: AppColors.meaning_color_danger,
            ),
          ),
          Text(
            '作业负责人',
            style: TextStyle(
              fontSize: 14.sp,
              color: AppColors.font_color_black,
            ),
          ),
        ],
      ),
    );
  }

  // 获取监护人姓名
  String _getGuardianUserName(ApplyUserEntity entity) {
    if (entity.guardianList.isEmpty) {
      return '请选择';
    }
    return entity.guardianList.map((e) => e.operatorUserName).join(',');
  }

  // 涉及作业申请人
  Widget _fireRequestList() {
    return Container(
      alignment: Alignment.centerLeft,
      child: Column(
        children: controller.selectedJobApplicant
            .map(
              (e) => Column(
                children: [
                  _selectWidget('${e.selectedJobList}申请人', e.applyUserName ?? '请选择', callback: () {
                    controller.queryApplicant(roleName: '作业申请人', type: e.selectedJobList ?? '', bean: e);
                  }, isVisibility: false),
                  _selectWidget('${e.selectedJobList}监护人', _getGuardianUserName(e), callback: () {
                    controller.queryApplicant(roleName: '监护人', type: e.selectedJobList ?? '', bean: e);
                  }, isVisibility: false),
                ],
              ),
            )
            .toList(),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView(
        child: GetBuilder(
            init: controller,
            builder: (_) {
              return Column(
                children: [
                  Container(
                    height: 16.w,
                    color: AppColors.bg_color_grey,
                  ),
                  _selectWidget('风险辨识结果', '请选择', callback: () {
                    _selectRiskIdentificationResult();
                  }),
                  _riskIdentificationResultWidget(),
                  _selectWidget('工具集', '请选择', callback: () {
                    controller.selectToolSet();
                  }),
                  _toolSetWidget(),
                  AppGaps.vGap10,
                  Visibility(
                      visible: controller.isConfirm.value,
                      child: Column(
                        children: [
                          Container(
                            height: 18.w,
                            color: AppColors.bg_color_grey,
                          ),
                          _nextButton(),
                          _involvedOperation(),
                          _applicant(),
                          _fireRequestList(),
                        ],
                      )),
                  AppGaps.vGap64
                ],
              );
            }),
      ),
      bottomSheet: Container(
        height: 50.w,
        width: double.infinity,
        color: Colors.white,
        padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 5.w),
        child: ElevatedButton(
          style: ElevatedButton.styleFrom(
            backgroundColor: AppColors.blue_button,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(22.r),
            ),
          ),
          onPressed: controller.nextOrConfirm,
          child: Obx(() {
            return Text(
              controller.isConfirm.value ? '确定' : '下一步',
              style: TextStyle(
                fontSize: 16.sp,
                color: Colors.white,
              ),
            );
          }),
        ),
      ),
    );
  }
}
